<template>
  <div class="createPost-container">
    <div class="filter-container">
      <el-form
        ref="listQuery"
        :model="listQuery"
        class="search-form"
        inline
        label-width="78px"
        align="right"
      >
        <el-form-item
          label="任务名称:"
          prop="title"
        >
          <el-input
            v-model="listQuery.title"
            size="small"
            placeholder="请输入"
            clearable
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item
          label="上报类别:"
          prop="data_type"
        >
          <el-select
            v-model="listQuery.data_type"
            size="small"
            placeholder="请选择"
            clearable
            @change="handleFilter"
          >
            <el-option
              v-for="item in taskTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="日期范围:"
          prop="date"
        >
          <el-date-picker
            v-model="listQuery.date"
            type="daterange"
            size="small"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="handleFilter"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="任务类别:"
          prop="classify"
        >
          <el-select
            v-model="listQuery.classify"
            size="small"
            placeholder="请选择"
            clearable
            @change="handleFilter"
          >
            <el-option
              v-for="item in reportTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="紧急程度:"
          prop="emergency_level"
        >
          <el-select
            v-model="listQuery.emergency_level"
            size="small"
            placeholder="请选择"
            clearable
            @change="handleFilter"
          >
            <el-option
              v-for="item in importantOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="子任务:"
          prop="childs"
        >
          <el-select
            v-model="listQuery.childs"
            size="small"
            placeholder="请选择"
            clearable
            @change="handleFilter"
          >
            <el-option
              label="包含"
              value="包含"
            />
            <el-option
              label="不包含"
              value="不包含"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="处理人:"
          prop="user"
        >
          <el-input
            v-model="listQuery.user"
            size="small"
            placeholder="请输入"
            list="cars"
            class="user-input"
            clearable
            @input="handChangeUser"
            @keyup.enter.native="handleFilter"
          />
          <datalist id="cars">
            <option
              v-for="(item, index) in dataList"
              :value="item"
              :key="index"
            ></option>
          </datalist>
        </el-form-item>
        <!-- <div style="width: 350px; height: 0"></div> -->
        <el-form-item class="search-form__toolbox">
          <el-button
            size="small"
            type="primary"
            @click="handleFilter"
          >查询</el-button>
          <el-button
            size="small"
            style="margin-right: 6px;"
            @click="resetForm('listQuery')"
          >重置</el-button>
          <!-- <el-button type="text" @click="_toggleShowMore">
                {{ searchShowMore ? '收起' : '展开'}}
                <i :class="searchShowMore ? 'el-icon-arrow-up': 'el-icon-arrow-down'"></i>
              </el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div class="btngroup">
      <el-dropdown size="small" trigger="click">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
        >
          新增<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="handleCreateTask">普通任务</el-dropdown-item>
          <el-dropdown-item @click.native="handleCreateFilePrint">材料审批</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <!-- <el-button size="small" type="primary" icon="el-icon-plus" @click="handleCreateTask">新增</el-button> -->
      <el-button
        size="small"
        icon="el-icon-edit"
        @click="handleUpdateTask"
        :disabled="multipleSelection.length !== 1 || !multipleSelection[0].is_edit"
      >编辑</el-button>
      <el-button
        size="small"
        icon="el-icon-delete"
        @click="handleDelTask"
        :disabled="multipleSelection.length == 0"
      >删除</el-button>
      <el-button
        size="small"
        icon="el-icon-upload"
        @click="handlePublish"
        :disabled="multipleSelection.length !== 1 || multipleSelection[0].is_publish"
      >发布</el-button>
    </div>
    <div class="task-items">
      <el-table
        :data="taskList"
        stripe
        style="width: 100%;"
        size="small"
        row-key="id"
        v-loading="listLoading"
        :tree-props="{children: 'child'}"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" class="demo-table-expand"> 
              <el-form-item label="安排用户">
                <span>32人</span>
              </el-form-item>
              <el-form-item label="上报用户">
                <span>14人</span>
              </el-form-item>
              <el-form-item label="上报文件" style="padding-right: 9px;">
                <span>7个</span>
              </el-form-item>
              <el-form-item label="任务进度" style="padding-left:33px;">
                <template>
                  <el-progress type="dashboard" :width="60" :percentage="50"></el-progress>
                </template>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column> -->
        <el-table-column
          type="selection"
          width="40"
        ></el-table-column>
        <!-- <el-table-column prop="id" label="编号" width="60"></el-table-column> -->
        <el-table-column
          label="任务名称"
          min-width="280"
          align="left"
        >
          <template slot-scope="{row}">
            <div
              class="task-items__name"
              :style="{ marginLeft: row.child.length || row.parent? 0 : 17 + 'px'}"
              @click="linkToDetail(row)"
            >
              <!-- <img v-if="!row.child.length && row.parent" :src="require('@/assets/images/child.png')" style="vertical-align: super;width: 10px;"></img> -->
              <i
                v-if="!row.child.length && row.parent"
                class="el-icon-medal"
                style="color:#409EFF"
              ></i>
              <span
                class="top"
                v-if="row.is_top"
              >顶</span>
              <span class="">{{ row.title }}</span>
              <p
                class="overdue-text"
                v-if="row.overdue === '逾期'"
              >{{ row.overdue }}</p>
              <p
                class="overdue-text target"
                v-if="row.target"
              >指标</p>
              <p
                class="overdue-text approval"
                v-if="row.is_approval"
              >审批</p>
              <p
                class="overdue-text no-pub"
                v-if="!row.is_publish"
              >未发布</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="data_type"
          label="上报类型"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="classify_name"
          label="任务类别"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="emergency_level"
          label="紧急程度"
          min-width="100"
        >
          <template slot-scope="{row}">
            <el-tag :type="row.emergency_level | tagType">
              {{ row.emergency_level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="截至日期"
          min-width="150"
        >
          <template slot-scope="{row}">
            <span>{{ parseTime(row.end_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建人"
          min-width="80"
        >
          <template slot-scope="{row}">
            <span><i class="el-icon-user"></i> {{ row.owner }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="100"
          fixed="right"
        >
          <template slot-scope="scope">
            <!-- <router-link :to="'/task-center/preview/'+scope.row.id">
              <el-button type="text" size="small">查看</el-button>
            </router-link>
            <router-link :to="'/task-center/edit/'+scope.row.id">
              <el-button :disabled="scope.row.is_publish" type="text" size="small">编辑</el-button>
            </router-link>
            <el-button type="text" size="small" @click="tagTaskDel(scope.row.id)">删除</el-button> -->
            <!-- <el-button type="text" size="small" @click="toStaticsTask(scope.row)">统计</el-button> -->
            <!-- <router-link :to="'/task-center/statics/'+scope.row.id + '/?type=' + scope.row.data_type">
            </router-link> -->
            <!-- <el-button type="text" size="small" @click="toChildTask(scope.row)">分解</el-button> -->
            <!-- <el-button type="text" size="small" @click="showProcessDialog(scope.row.id)">流程监控</el-button> 
            <el-button type="text" size="small" :disabled="scope.row.is_edit" @click="showUserDialog(scope.row)">人员安排</el-button> -->
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                更多菜单<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  :disabled="!scope.row.is_publish"
                  @click.native="toStaticsTask(scope.row)"
                >数据统计</el-dropdown-item>
                <el-dropdown-item @click.native="toChildTask(scope.row)">任务分解</el-dropdown-item>
                <el-dropdown-item
                  :disabled="!scope.row.is_publish || !scope.row.is_approval"
                  @click.native="showProcessDialog(scope.row)"
                >流程监控</el-dropdown-item>
                <el-dropdown-item
                  :disabled="!scope.row.is_edit"
                  @click.native="showUserDialog(scope.row)"
                >人员安排</el-dropdown-item>
                <template>
                  <el-dropdown-item
                    v-if="!scope.row.is_top"
                    @click.native="handTaskTop(scope.row.id, true)"
                  >任务置顶</el-dropdown-item>
                  <el-dropdown-item
                    v-else
                    @click.native="handTaskTop(scope.row.id, false)"
                  >取消置顶</el-dropdown-item>
                </template>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        class="pageWrapper"
        v-show="total>0"
        :total="total"
        :layout="'total, prev, pager, next'"
        :page.sync="listQuery.page"
        :limit.sync="pageSize"
        @pagination="handlePage"
      />
    </div>
    <div class="approve-wrapper">
      <el-dialog
        title="发布"
        width="400px"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          ref="postForm"
          class="approve-form"
        >
          <!-- <el-form-item label-width="97px" class="postInfo-container-item" label="是否需要审批">
                  <el-switch v-model="isApprove"> </el-switch>
                </el-form-item> -->
          <el-form-item class="postInfo-container-item">
            <el-select
              v-model="approve"
              placeholder="请选择审批流程"
              size="small"
              clearable
              style="width: 100%;"
            >
              <el-option
                v-for="(item, index) in processList"
                :label="item.name"
                :value="item.key"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            @click="dialogFormVisible = false"
            size="small"
          >取 消</el-button>
          <el-button
            type="primary"
            @click="handSelectApprove"
            size="small"
          >确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 流程监控 -->
    <process-monitor
      ref="process"
      :fromTask="true"
      :pager="selectedRecord"
      :activities="activities"
      :processStatics="processStatics"
    ></process-monitor>
    <!-- 打开人员安排窗口  -->
    <div class="">
      <el-dialog
        width="80%"
        title="人员安排"
        :visible.sync="dialogUserVisible"
      >
        <user-manager
          :relateUsers="relateUsers"
          :showSaveSelectedUser="false"
          ref="userManager" 
        />
        <el-row
          type="flex"
          justify="center"
          style="margin-top:15px;"
        >
          <el-button
            type="primary"
            size="small"
            @click="handRelatePerson"
          >保存</el-button>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import _ from 'lodash'
import {
  getTashList,
  updateTaskPart,
  delTask,
  getTaskClassify
} from "@/api/work.js";
import {
  getProcess,
  startProcess,
  completeTasks,
  delProcessDataByTaskId,
  getTaskProcessInfo1,
  getTaskIdInByBus,
  getTaskInfoByUserIdAndProcessId,
  getTaskInfoByUserIdAndTaskId
} from "@/api/workflow.js";
import {
  filterObj,
  getFirstDayOfWeek,
  getFirstDayOfMonth,
  getFirstDayOfSeason,
  getFirstDayOfYear
} from "@/utils/index.js";
import axios from "axios";
import Cookies from "js-cookie";
import { parseTime } from "@/utils";

let isFormDetail = false;
export default {
  name: "taskCenter",
  computed: {
    ...mapGetters([
      "name",
      "roles",
      "department",
      "id",
      "circulation_user",
      "filterParam"
    ]),
    isPub() {
      return this.multipleSelection.every(e => e.is_publish);
    }
  },
  components: {
    Pagination: require("@/components/Pagination").default,
    UserManager: () => import("./components/userManager"),
    "process-monitor": () =>
      import("./approve/handler/components/ProcessMinitor/index.vue")
  },
  data() {
    return {
      taskId: null, // 任务ID
      currentPage: 1,
      total: 0,
      pageSize: 10,
      dataList: [], // 输入框记录历史
      listLoading: true,
      isContainsSub: null, // 是否包含子任务
      listQuery: {
        page: 1,
        title: "",
        classify: "",
        data_type: "",
        emergency_level: "",
        childs: "",
        user: "",
        date: []
      },
      canPublish: true,
      approve: "", // 审批流程
      processList: [], // 审批流程列表
      fileYearOptions: ["2020", "2019", "2018"],
      reportTypeOptions: [],
      taskTypeOptions: ["通知", "文件上传", "表格填报", "测评问卷"],
      importantOptions: ["紧急", "重要", "常规"],
      dialogFormVisible: false,
      dialogUserVisible: false, // 人员安排
      relateUsers: [], // 初始任务关联人员
      updateUsers: [], // 重新选择的人员
      multipleSelection: [],
      taskList: [],
      processStatics: {
        curCount: 0,
        doneCount: 0,
        willCount: 0
      }, // 流程监控节点统计
      activities: [], // 流程监控数据
      selectedRecord: null, // 选中记录
      pickerOptions: {
        // 自定义时间范围
        shortcuts: [
          {
            text: "本周",
            onClick(picker) {
              const end = new Date();
              picker.$emit("pick", [getFirstDayOfWeek(new Date()), end]);
            }
          },
          {
            text: "本月",
            onClick(picker) {
              const end = new Date();
              picker.$emit("pick", [getFirstDayOfMonth(new Date()), end]);
            }
          },
          {
            text: "本季",
            onClick(picker) {
              const end = new Date();
              picker.$emit("pick", [getFirstDayOfSeason(new Date()), end]);
            }
          },
          {
            text: "本年",
            onClick(picker) {
              const end = new Date();
              picker.$emit("pick", [getFirstDayOfYear(new Date()), end]);
            }
          }
        ]
      }
    };
  },
  created() {
    if (isFormDetail) {
      Object.assign(this.listQuery, this.filterParam);
      let open = false;
      Object.keys(this.listQuery).forEach(key => {
        if (key !== "page" && key !== "date") {
          if (this.listQuery[key]) {
            open = true;
          }
        }
      });
      this.searchShowMore = open;
    }
  },
  mounted() {
    this.requestTaskList();
    this.getProcessList();
    this.requestTaskClassify();
    this.dataList = JSON.parse(localStorage.getItem("dataList"));
  },
  methods: {
    parseTime,
    // 判断屏幕宽度，搜索项是否显示
    $_isShowColumn() {
      const rect = document.body.getBoundingClientRect();
      return rect.width - 1 > 1590;
    },
    handChangeUser(val) {
      this.dataList = JSON.parse(localStorage.getItem("dataList"));
    },
    // 点击发布
    handlePublish() {
      const { is_normal } = this.multipleSelection[0]
      // 普通任务 直接发布
      if(is_normal) {
        // 显示发布确认框
        this.$confirm("确认要发布此任务吗？").then((res) => {
          this.approve = 'TYFB001'
          this.handSelectApprove() // 启动任务
        });
      } else {
        // 材料审批任务
        this.dialogFormVisible = true
      }
    },
    /*
     * 缓存输入框记录
     * param: String; 对象字段名称
     */
    saveInputSession(param) {
      const value = this.listQuery[param];
      if (!value) return;
      var locData = JSON.parse(localStorage.getItem("dataList"));
      if (!locData || !locData.includes(value)) {
        if (!locData) {
          localStorage.setItem("dataList", JSON.stringify([value]));
        } else {
          if (locData.length > 4) {
            locData = locData.slice(locData.length - 4, locData.length);
          }
          localStorage.setItem(
            "dataList",
            JSON.stringify(locData.concat([value]))
          );
        }
      }
    },
    /*
     * 任务置顶
     * type: true为将任务置顶，false则取消置顶
     */
    handTaskTop(id, type) {
      const isTop = type ? "True" : "False";
      const optionDesc = type ? "任务置顶" : "取消置顶";
      updateTaskPart(id, { is_top: isTop }).then(res => {
        this.$notify({
          title: "成功",
          message: `${optionDesc}操作成功`,
          type: "success",
          duration: 2000
        });
        this.requestTaskList();
      });
    },
    // 跳转到任务详情
    linkToDetail(row) {
      const { id, is_approval, is_publish } = row;
      this.$router.push({
        name: "PreviewTask",
        params: {
          id,
          targetId: id,
          isHand: true,
          showPager: is_approval && is_publish,
          fromRoute: 'taskList' // 指定从任务列表页面跳转过去
        }
      });
      this.$store.dispatch("param/setSearchFilter", this.listQuery);
    },
    // 重置搜索框
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.handleFilter();
    },
    // 切换显示更多搜索框
    _toggleShowMore() {
      this.searchShowMore = !this.searchShowMore;
    },
    isSinglePoint(row) {
      return !row.child.length && !row.parent;
    },
    handleFilter() {
      this.saveInputSession("user");
      this.listQuery.page = 1;
      this.requestTaskList(!this.paramIsNull());
    },
    paramIsNull() {
      let falg = true;
      const query = JSON.parse(
        JSON.stringify(this.listQuery, [
          "title",
          "classify",
          "data_type",
          "emergency_level"
        ])
      );
      Object.keys(query).forEach(key => {
        if (this.listQuery[key]) {
          falg = false;
        }
      });
      return falg;
    },
    // 打开流程监控窗口
    showProcessDialog(row) {
      const taskId = row.id
      this.selectedRecord = row
      getTaskProcessInfo1(taskId).then(res => {
        const { curCount, doneCount, willCount, proDefKey, data } =
          (res.data && res.data.data) || {};
        this.activities = data;
        this.processStatics = {
          taskId: taskId,
          modelName: proDefKey,
          curCount: curCount,
          doneCount: doneCount,
          willCount: willCount
        };
      });
      this.$refs.process.dialogProcessVisible = true;
      this.$refs.process.togglePage = false;
    },
    // 分页
    handlePage(val) {
      this.listQuery.page = val.page;
      this.requestTaskList(!this.paramIsNull());
    },
    // 打开人员安排对话框
    showUserDialog(row) {
      this.dialogUserVisible = true;
      this.taskId = row.id;
      this.relateUsers = this.transformObject(row.user, row.username);
    },
    // 重新关联任务人员
    handRelatePerson() {
      const users = this.$refs.userManager.sureUsersList
      if (users.length) {
        const userId = users.map(e => e.id);
        updateTaskPart(this.taskId, { user: userId }).then(res => {
          this.$notify({
            title: "成功",
            message: "修改任务安排人员成功",
            type: "success",
            duration: 2000
          });
          this.requestTaskList(!this.paramIsNull());
          this.dialogUserVisible = false;
        });
      }
    },
    // 用户名 id 键值绑定
    transformObject(keyArr, valueArr) {
      let arr = [];
      keyArr.forEach((v, i) => {
        arr.push({
          id: keyArr[i],
          username: valueArr[i]
        });
      });
      return arr;
    },
    // 表格行操作
    tagTaskDel(id) {
      this.$confirm("此操作将删除任务, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.postTaskDel(id);
      });
    },
    // 跳转到任务统计
    toStaticsTask(row) {
      this.$router.push({
        name: "StaticsTask",
        query: {
          targetId: row.id,
          type: row.data_type,
          title: row.title,
          superior: row.issued_superior
        }
      });
    },
    // 跳转到创建子任务
    toChildTask(row) {
      // this.$router.push({name:'CreateTask',params:{parent:row.id, title: row.title, content: row.body, dataType: row.data_type, }})
      this.$router.push({
        name: "CreateTask",
        params: { parent: row.id, initData: row }
      });
    },
    // 新增普通任务
    handleCreateTask() {
      this.$router.push({ name: "CreateTask" });
    },
    // 新增文件印发任务
    handleCreateFilePrint() {
      this.$router.push({ name: "CreateFilePrint" });
    },
    handleUpdateTask() {
      const { id, is_approval } = this.multipleSelection[0];
      if(is_approval) {
        // 如果是审批任务
        this.$router.push({ path: "/task-center/createFilePrint", query: {taskId: id} });
      } else {
        // 普通任务
        this.$router.push({ path: `/task-center/edit/${id}` });
      }
    },
    // 删除任务
    handleDelTask() {
      this.$confirm("此操作将删除任务, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let queue = this.multipleSelection.map(item => {
          return new Promise((resolve, reject) => {
            delProcessDataByTaskId(item.id).then(res => {
              if (res && res.data && res.data.code == "200") {
                delTask(item.id).then(res => {
                  resolve();
                });
              }
            });
          });
        });
        Promise.all(queue)
          .then(result => {
            //执行后续操作
            this.$message.success("删除任务成功");
            this.requestTaskList();
          })
          .catch(error => {
            this.$message.danger("删除任务失败");
          });
        // this.multipleSelection.forEach(item=>{
        //   this.postTaskDel(item.id)
        // })
      });
    },
    // 确定流程
    handSelectApprove() {
      // if(this.isApprove){
      // 需要审批
      if (!this.approve) {
        this.$message.warning("审批流程不能为空");
        return;
      }
      this.executeApprove();
      // }else{
      //   // 不审批，直接发布
      //   this.multipleSelection.forEach(item=>{
      //       this.postTaskPublish(item.id, 'True')
      //     })
      // }
    },
    // 执行流程
    executeApprove() {
      // 保存公文基本信息
      const item = this.multipleSelection[0];
      if (!item.is_approval && !item.user.length) {
        this.$message.warning("发布任务前请先选择人员");
        return;
      }
      // 通过流程key 匹配对应流程process对象
      const targetApprove = _.find(this.processList, {key: this.approve})
      
      const param = {
        businessKey: item.id,
        bussinesskey: item.id,
        bussName: item.title,
        bussType: "SP",
        targetUnitId: "",
        startUserId: this.id,
        startUserName: this.name,
        emergency: item.emergency_level,
        classify_name: item.classify_name,
        is_normal: item.is_normal,
        end_time: item.end_time,
        userList: item.user,
        circulation_user: this.circulation_user
      };
      // 流程对象有值，将描述保存到流程中，用于判断是否是州委办收文
      if(targetApprove) {
        param.processDesc = targetApprove.description
      }
      startProcess(this.approve, param).then(async res => {
        if (res && res.data.message === "启动成功") {
          this.$notify({
            title: "成功",
            message: "启动流转成功",
            type: "success",
            duration: 2000
          });
          // 如果是州委收文流程
          if(targetApprove && targetApprove.description) {
            // 修改任务approval_type类型
            await updateTaskPart(item.id, { approval_type: targetApprove.description });
          }
          if (this.approve.startsWith("TSP")) {
            const { processId } = res.data.data;
            getTaskInfoByUserIdAndProcessId({
              assignee: this.id,
              processId
            }).then(res => {
              const { id, name, procDefId, procInstId, taskDefKey, formKey, variables } =
                res.data && res.data.data;
              this.$router.push({
                name: "HandlerPager",
                params: {
                  type: "handler",
                  id: id,
                  nodeName: name,
                  proDefId: procDefId,
                  proInsId: procInstId,
                  startUserId: this.id || "",
                  targetId: item.id,
                  rejectKey: taskDefKey,
                  isTSP: true,
                  formKey: formKey || '',
                  variables,
                  isHand: false
                }
              });
              return;
            });
          }
          // const type = this.approve.slice(0, 2)
          // if(type === 'SP'){
          // getTaskIdInByBus({userId: this.id, bussKey: item.id}).then(
          //   res =>{
          //       const { id, procDefId, procInstId, taskDefKey} = res.data && res.data.data
          //       this.$router.push({
          //         name: 'HandlerPager',
          //         params: {
          //           type: 'handler',
          //           id: id,
          //           proDefId: procDefId,
          //           proInsId: procInstId,
          //           startUserId: this.id || '',
          //           targetId: item.id,
          //           rejectKey: taskDefKey,
          //           isHand: false
          //         }
          //       })
          //     }
          //     )
          //   }
          this.multipleSelection.forEach(item => {
            // let flag = type === 'SP' ? true: false
            this.postTaskPublish(item.id);
          });
        } else {
          this.$notify({
            title: "失败",
            message: "启动流转失败",
            type: "error",
            duration: 2000
          });
        }
      });
    },
    nextStep() {
      if (this.index++ > 1) this.active = 0;
    },
    preStep() {
      if (this.index-- < 0) this.active = 1;
    },
    // 表格多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 提交删除任务
    postTaskDel(id) {
      delTask(id).then(res => {
        this.$message({
          message: "删除任务成功！",
          type: "success"
        });
        this.requestTaskList();
      });
    },
    // 提交修改任务发布状态
    postTaskPublish(id) {
      const param = {
        is_publish: 'True',
        is_approval: this.approve === "TYFB001" ? 'False' : 'True'
      }
      updateTaskPart(id, param).then(res => {
        if (res && res.data && res.data.title) {
          this.$notify({
            title: "提示",
            message: `发布任务成功`,
            type: "success",
            duration: 2000
          });
          this.dialogFormVisible = false;
          this.requestTaskList();
        } else {
          this.$message.error("发布任务失败");
        }
      });
    },
    // 请求审批流程列表
    getProcessList() {
      // 获取模型列表
      getProcess(this.department).then(res => {
        this.processList = res.data.data;
      });
    },
    // 请求上报类别列表
    requestTaskClassify() {
      getTaskClassify().then(res => {
        const classifyList = res.data.results
        // 筛选task类别
        this.reportTypeOptions = classifyList.filter(item => item.type !== 'schedule')
      });
    },
    // 子任务归类
    formatData(data) {
      return data.filter(e => !e.parent);
    },
    getUsersList(data, result) {
      data.forEach(item => {
        // result = [...result, ...item.user_department]
        item.child.forEach(user => {
          result.push(user);
        });
        if (item.child && item.child.length > 0) {
          this.getUsersList(item.child, result);
        }
      });
      return result;
    },
    allIsParent(data) {
      if (data.length === 1 || data.length === 0) {
        return true;
      } else {
        return data.every(e => e.parent);
      }
    },
    requestTaskList(isSearch = false) {
      this.listLoading = true;
      let owner = { owner: this.id };
      let date = {};
      if (this.listQuery.date && this.listQuery.date.length) {
        date = {
          date_begin: parseTime(this.listQuery.date[0], "{y}-{m}-{d}"),
          date_end: parseTime(this.listQuery.date[1], "{y}-{m}-{d}")
        };
        // this.listQuery.date = null;
      }
      const queryParam = Object.assign({}, this.listQuery, date);
      const data = filterObj(queryParam);
      const param = Object.assign(owner, data);
      getTashList(param).then(res => {
        const { results, count } = res.data;
        this.taskList = results;
        this.total = count;
        this.listLoading = false;
      });
    }
  },
  beforeRouteEnter: function(to, from, next) {
    if (from.name == "PreviewTask") {
      isFormDetail = true;
    }
    next();
  },
  beforeDestroy() {
    isFormDetail = false;
  }
};
</script>
<style lang="scss">
.createPost-container {
  padding: 20px;
  .btngroup {
    margin-top: 10px;
  }
  .user-input{
    input{
      padding-right: 0 !important;
      line-height: 12px;
    }
    .el-input__suffix {
      width: 36px;
      text-align: center;
    }
  }
  .task-items {
    margin-top: 20px;
    .overdue-text {
      display: inline-block;
      padding: 2px;
      margin: 0;
      margin-right: -2px;
      transform: scale(0.9);
      font-size: 12px;
      background: #a0cfff;
      color: #fff;
      background: #ff7a73;
      border-radius: 2px;
      line-height: 12px;
    }
    &__name {
      cursor: pointer;
      &:hover {
        color: #409eff;
      }
    }
    .top {
      background: #f4ea2a;
      color: #fff;
      padding: 2px;
      border-radius: 2px;
    }
    .no-pub {
      background: #a0cfff;
    }
    .target {
      background: #b3e19d;
    }
    .approval {
      background: rgb(255, 119, 2);
    }
    .el-button--text {
      margin-right: 2px;
    }
    .el-dropdown-link {
      cursor: pointer;
      color: #409eff;
    }
    .el-dropdown-link,
    .el-icon-arrow-down {
      font-size: 12px;
    }
  }
  .search-form,
  .approve-form {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
  .search-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    &__toolbox {
      width: 280px;
      /* margin-left: auto; */
      .el-button {
        margin-right: 4px;
      }
    }
    @media screen and (min-width: 1560px) {
      &__toolbox {
        margin-left: auto;
      }
    }
    .el-form-item__label {
      font-weight: normal !important;
    }
    .el-input--small .el-input__inner {
      width: 200px;
    }
    .el-range-editor--small.el-input__inner {
      width: 228px;
    }
  }
  .el-table__expand-icon {
    width: 14px !important;
  }
  .el-button + .el-button {
    margin-left: 0;
  }
  .el-table .cell {
    display: flex;
  }
  .el-table thead tr th:nth-child(2) {
    padding-left: 16px;
  }
  .el-dialog__body {
    padding: 10px 20px 10px;
  }
  .pageWrapper {
    padding: 10px;
  }
}
</style>
<style>
/* .demo-table-expand {
     font-size: 0; 
     display: flex;
    flex-wrap: wrap;
    padding: 10px 57px 0;
  }
  .demo-table-expand label {
    width: 70px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50%;
  }
  .demo-table-expand .el-form-item:last-child(){
    padding-left: 32px;
  } */
/* .el-table td, .el-table th{
    padding: 10px 0;
    text-align: center!important;
  }
  .el-table__expanded-cell{
    padding:0!important;
  } */
/*修改标签颜色*/
.el-tag.el-tag--warning {
  color: #ff5200;
}
.el-tag.el-tag--success {
  background-color: #eeffe4;
  border-color: #b3c7a942;
  color: #559634;
}
.el-tag.el-tag--danger {
  background-color: #ffe2e2;
  border-color: #d4b3b369;
  color: #ff1515;
}
.el-button--text {
  color: #2076ce;
}
</style>
